;; Copyright (C) 2021 Maxime Devos
;; SPDX-License-Identifier: FSFAP
;; Copying and distribution of this file, with or without modification,
;; are permitted in any medium without royalty provided the copyright
;; notice and this notice are preserved.  This file is offered as-is,
;; without any warranty.

(use-modules (fibers)
	     (gnu gnunet config db)
	     (gnu gnunet config fs)
	     (rnrs hashtables)
	     ((gnu gnunet nse client)
	      #:prefix #{nse:}#)
	     ((gnu gnunet dht client)
	      #:prefix #{dht:}#)
	     (web server)
	     (srfi srfi-11))

(define config (load-configuration))

(define (url-handler server request body)
  (define current-estimate (nse:estimate server))
  (define body
    (if current-estimate
	(format #f "timestamp: ~a~%number peers: ~a~%stddev logarithm: ~a"
		(nse:estimate:timestamp current-estimate)
		(nse:estimate:number-peers current-estimate)
		(nse:estimate:standard-deviation current-estimate))
	"no estimate available yet ..."))
  (values '((content-type text/plain)) body #f))

(define (start config)
  (define nse-server (nse:connect config))
  (define dht-server (dht:connect config))
  (define impl (lookup-server-impl 'fiberized))
  (define server (open-server impl `(#:port 8089)))
  (define (url-handler* request body)
    (url-handler nse-server request body))
  (let loop ()
    (let-values (((client request body)
		  (read-client impl server)))
      (spawn-fiber
       (lambda ()
	 (let-values (((response body state)
		       (handle-request url-handler* request body '())))
	   (write-client impl server client response body)))))
    (loop)))

(run-fibers (lambda () (start config)))
